#!/usr/bin/env python
# -*- coding: utf-8 -*-
from StringIO import StringIO
from extensions.langs.auto import Extend as AutoLang
from core.ide.datamangager import DataMangager, DataInfos
import wx.stc as stc
import context
import re
import subprocess
import wx
import os.path
from core.ide.commandmanager import CommandManager

class Extend():
    def __init__(self):
        self.name='Python'
        data=DataMangager().getData("Python", "Python Path", "")
        data.type=DataInfos.FILE
        #section,name,defaulValue=None,defaulValues=None,defaulCategory="Generic"
        self._ready=False
        
        data=DataMangager().getData("Python", "Python Version",2.7)
        data=DataMangager().getData("Python", "hidde prefix", "__", None, "Completion")
        self.hidePrefix=data.value
        DataMangager().getData("Python", "Space indent", 4,None, 'Editor')
        DataMangager().getData("Python", "Repleace tab by space", True, None, 'Editor')
    
    def getSeparator(self):
        return ' .:\"\''
        
    def AutoCompletionAfter(self):
        return ["."]
    
    def getTemplates(self):
        return ["python/templates/python.py"]
    
    
    def isReady(self):
        return self._ready        
        
    def close(self):
        pass
    
    def getStyles(self):
        style={
          0:"fore:#999900",
          1:"fore:#666666", #Comment
          2:"fore:#8b0000", #Number
          3:"fore:#000099", #"string"
          4:"fore:#000099", #'string'
          5:"fore:#871f78", #stc.STC_P_WORD
          6:"fore:#000099", # '''...'''
          7:"fore:#000099",# """..."""
          8:"fore:#009090", #Class name
          9:"fore:#009090",  #def name
          10:"fore:#000000", #{}=+
          11:"fore:#000000", #Default text   
          12:"fore:#666666", ##Comment
          13:"fore:#990099",
          14:"fore:#c1670d", #stc.STC_P_WORD2
          13:"fore:#0099FF",
          15:"fore:#006600", #@modifier
          16:"fore:#99FF99",
          17:"fore:#99FF99",
          18:"fore:#99FF99",
          19:"fore:#99FF99",
          20:"fore:#99FF99",
          
          }
        return style
    
    def getMode(self):
        return ["Release", "Debug","Application"]

    def checkSyntaxe(self,txt):
        #(error,message,start,end)
        return [(1,"message",0,0)]
        
    def applyAutoSyntaxe(self,txt):
        
        return txt
    
    def getLexer(self):
        return stc.STC_LEX_PYTHON
    
    def getSourceFileNames(self): 
        return ["*.py", "*.pyw"]
    
    def read(self,text,path):
        self.cr=context.CodeReader()
        self.cr.read(text,path)
    
    def getLineContext(self,lineNumber,line):
        ctx=self.cr.readLine(line,lineNumber)
        if not ctx:
            ctx=self.cr.getLastContextByLine(lineNumber)
            if not ctx.canHasChild() and ctx.parent:
                ctx=ctx.parent
        return ctx
    
    def getCompletion(self,lineNumber,line):
        self.hidePrefix=DataMangager().getValue("Python", "hidde prefix")
        line=line.strip()
        try:
            ctx=self.getLineContext(lineNumber,line)
        except:
            pass
        if not ctx:
            ctx=self.getRootContext()
        wordsList=[]
        exp=re.search("[^ ^\t]+",line)
        if exp is None:
            wordsList+=ctx.getChilds()
        elif line.find(".")>-1:
            line2=line
            if line.count("(")!=line.count(")"):
                line2=re.split("[\( ]",line2)[-1]
            #else:
            #    line2=re.sub("\([^)]*\)","",line2)
            if line.count("[")!=line.count("]"):
                line2=re.split("[\[ ]",line2)[-1]
            #else:
            #    line2=re.sub("\[[^\]]*\]","",line2)
            
            while line2[0]==" " or line2[0]=="\t":
                line2=line2[1:]
            splitDot=line2.split(".")#[0:-1]
            ctx2=ctx
            called=False
            for word in splitDot:
                if not word:
                    continue
                if line2.count("[")==line2.count("]") and line2.count("]"):
                    word=re.sub("\[[^\]]*\]","",word)
                if line2.count("(")==line2.count(")") and line2.count(")"):
                    called=True
                    word=re.sub("\([^)]*\)","",word)
                if ctx.name==word:
                    ctx2=ctx
                else:
                    ctx2=ctx2.getChild(word)
                
                
                
                if not ctx2 and self.cr.getGlobal().has_key(word):
                    ctx2=self.cr.getGlobal()[word]
                    
                if called and ctx2.type!="class":
                    return []
                if not ctx2:
                    break    
            
        
            if not ctx2:
               pass
            elif ctx2.typeValue:
                wordsList+=ctx2.typeValue.getChilds()
            else:
                wordsList+=ctx2.getChilds()
        else:
            pass      
            
        ret=wordsList
        #for word in wordsList:
        #    if type(word) is not str:
        #        word=word.name
        #    if word[0:len(self.hidePrefix)]!=self.hidePrefix:
        #        ret.append(word)
        ret.sort()
        return ret   
    
    def getRootContext(self):
        return self.cr.root
    
    def getFileTabName(self,path):
        name=os.path.basename(path)
        if name=="__init__.py":
            path=path.replace("\\", "/")
            name=path.split("/")[-2]+"/"+name
        return name
    
    def execute(self,path):
        pathPython=DataMangager().getValue("Python", "Python Path")
        if pathPython!="":
            CommandManager().execute("execute",pathPython)
            #execCmd(pathPython)
    
    def build(self,path,folder=None):
        pass
    
    def run(self,path,mode="Release",folder=None):
        pathPython=DataMangager().getValue("Python", "Python Path")
        if pathPython!="" and mode=="Release":
            CommandManager().execute("execute",pathPython+" "+path,folder)
        elif pathPython!="" and mode=="Debug":
            CommandManager().execute("execute",
                                    pathPython+" -m extensions.langs.python.rpdb2 "+path,
                                    folder)
        else:
            print ("error python not found")
    
    def getKeyWord(self):
        keywords={}
        keywords[0]=["list", "dict", "isinstance", "int", "and", "del", "if", "else", "from", "for",
                    "fromnot", "while", "as", "elif", "global", "or", "with", "assert", "elseif",
                    "passyield", "break", "except", "import", "print", "class", "execin", "raise",
                    "continue", "finally", "is", "return", "def", "for", "lambda", "try","pass"]
        keywords[1]=["True", "False", "None", "object", "list", "str", "int", "unicode", "float"]
        return keywords


def execCmd(arg):
    proc = subprocess.Popen(arg, shell=False)

    return proc
    
    
def PythonOption():
    pass